package com.suncky.frame.base.mvvm;

import android.view.View;

import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.suncky.frame.base.BaseDataBindingActivity;

import java.lang.reflect.ParameterizedType;

public abstract class BaseMvvmActivity<B extends ViewDataBinding, VM extends BaseViewModel> extends BaseDataBindingActivity<B> {

    private VM viewModel;

    public VM getViewModel() {
        return viewModel;
    }
    @SuppressWarnings("unchecked")
    protected VM createViewModel() {
        try {
            // 获取当前对象的泛型的父类类型
            ParameterizedType pt = (ParameterizedType) (this.getClass().getGenericSuperclass());
            // 获取第二个类型参数的真实类型
            Class<VM> pClass = (Class<VM>) pt.getActualTypeArguments()[1];
            return new ViewModelProvider(getViewModelStoreOwner()).get(pClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected ViewModelStoreOwner getViewModelStoreOwner() {
        return this;
    }

    @Override
    protected View getContentView() {
        View view = super.getContentView();
        viewModel = createViewModel();
        if (viewModel != null) {
            viewModel.getLoadState().observe(this, new Observer<LoadState>() {
                @Override
                public void onChanged(LoadState loadState) {
                    onLoadStateChang(loadState);
                }
            });
        }
        return view;
    }


    private void onLoadStateChang(LoadState loadState) {
        if (loadState == null) {
            return;
        }
        switch (loadState.getState()) {
            case LoadState.PRE_LOAD:
                onPreLoad(loadState.getId(), loadState.getDesc());
                break;
            case LoadState.LOADING:
                onLoading(loadState.getId(), loadState.getDesc());
                break;
            case LoadState.FINISHED:
                onLoadFinish(loadState.getId(), loadState.getDesc());
                break;
        }
    }

    protected void onPreLoad(int id) {
        showLoadingPop();
    }

    protected void onLoading(int id) {

    }

    protected void onLoadFinish(int id) {
        dismissLoadingPop();
    }

    protected void onPreLoad(int id, String desc) {
        if (desc == null) {
            onPreLoad(id);
        } else {
            showLoadingPop(desc);
        }
    }

    protected void onLoading(int id, String desc) {
        if (desc == null) {
            onLoading(id);
        }
    }

    protected void onLoadFinish(int id, String desc) {
        if (desc == null) {
            onLoadFinish(id);
        } else {
            dismissLoadingPop();
        }
    }
}
